#include "UserProfile.h"
#include <QSqlQuery>
#include <QSqlError>
#include <QDebug>
#include "ui_UserProfile.h"

UserProfile::UserProfile(QWidget *parent)
    : QWidget(parent), ui(new Ui::UserProfile) {
    ui->setupUi(this);
    this->setStyleSheet("background-color: lightgreen;");
    // 初始化 UI 组件（如设置默认值或加载数据）
    ui->userIDLabel->setText("N/A");
    ui->startCityLabel->setText("N/A");
    ui->endCityLabel->setText("N/A");
    ui->sortLabel->setText("N/A");
    ui->travelLabel->setText("N/A");
}

UserProfile::~UserProfile() {
    delete ui;
}

void UserProfile::updateProfile(const QString& userID) {
    // 模拟获取用户画像数据并更新到 UI 上
    qDebug() << "Updating user profile for user ID:" << userID;

    analyzeJourneyData();
    // 更新到 UI 标签
    ui->userIDLabel->setText(userID);
    QString dCity = getFrequentDepartureCity();
    qDebug()<< dCity;
    ui->startCityLabel->setText(getFrequentDepartureCity());
    ui->endCityLabel->setText(getFrequentDestinationCity());
    ui->sortLabel->setText(getPreferredSortOption());
    ui->travelLabel->setText(getPreferredTripType());
}

void UserProfile::analyzeJourneyData() {
    QSqlDatabase db = AccountManager::getDatabase();
    if (!db.isOpen() && !db.open()) {
        qDebug() << "Failed to open database:" << db.lastError().text();
        return;
    }
    QString userID = SessionManager::getUserID();
    QSqlQuery query(db);
    query.prepare("SELECT start_city, end_city, sort_choice FROM journeys WHERE user_id = :userID");
    query.bindValue(":userID", userID);

    if (!query.exec()) {
        qDebug() << "Failed to fetch journey data:" << query.lastError().text();
        return;
    }

    while (query.next()) {
        QString departureCity = query.value(0).toString();

        QString destinationCity = query.value(1).toString();

        int sortChoice = query.value(2).toInt();

        // 更新出发城市和目的地城市的频率
        departureCityFrequency[departureCity]++;
        destinationCityFrequency[destinationCity]++;
        if (isInternational(destinationCity)) {
            internationalTrips++;
        } else {
            domesticTrips++;
        }

        // 更新排序偏好的频率
        QString sortOption = sortOptionToString(sortChoice);
        qDebug()<<sortOption;
        sortPreferences[sortOption]++;

    }
}

QString UserProfile::getPreferredTripType() const {
    if (internationalTrips > domesticTrips) {
        return "国际旅行";
    } else if (domesticTrips > internationalTrips) {
        return "大陆旅行";
    } else {
        return "均衡";
    }
}

QString UserProfile::getFrequentDepartureCity() const {
    if (departureCityFrequency.isEmpty()) {
        return "N/A";
    }

    QString frequentCity;
    int maxFrequency = 0;

    for (auto it = departureCityFrequency.constBegin(); it != departureCityFrequency.constEnd(); ++it) {
        if (it.value() > maxFrequency) {
            maxFrequency = it.value();
            frequentCity = it.key();
        }
    }
    qDebug()<<"The frequentCity is"+frequentCity;
    return frequentCity;
}

QString UserProfile::getFrequentDestinationCity() const {
    if (destinationCityFrequency.isEmpty()) {
        return "N/A";
    }

    QString frequentCity;
    int maxFrequency = 0;

    for (auto it = destinationCityFrequency.constBegin(); it != destinationCityFrequency.constEnd(); ++it) {
        if (it.value() > maxFrequency) {
            maxFrequency = it.value();
            frequentCity = it.key();
        }
    }
    qDebug()<<frequentCity;
    return frequentCity;
}

QString UserProfile::getPreferredSortOption() const {
    if (sortPreferences.isEmpty()) {
        return 0;
    }

    QString preferredOption;
    int maxFrequency = 0;

    for (auto it = sortPreferences.constBegin(); it != sortPreferences.constEnd(); ++it) {
        if (it.value() > maxFrequency) {
            maxFrequency = it.value();
            preferredOption = it.key();
        }
    }

    return preferredOption;
}

void UserProfile::printProfileSummary() const {
    qDebug() << "User Profile for User ID:" << userID;
    qDebug() << "Most Frequent Departure City:" << getFrequentDepartureCity();
    qDebug() << "Most Frequent Destination City:" << getFrequentDestinationCity();
    qDebug() << "Preferred Sort Option:" << getPreferredSortOption();
}

QString UserProfile::sortOptionToString(int sortOption) const {
    switch (sortOption) {
    case 1:
        return "最短时间";  // 最短时间
    case 2:
        return "最少花费";  // 最低花费
    case 3:
        return "直飞优先";  // 最少中转
    default:
        return "Unknown";  // 未知选项
    }
}

bool UserProfile::isInternational(const QString& destinationCity) const {
    static const QSet<QString> internationalDestinations = {
        "首尔", "东京", "马尼拉", "新加坡", "新德里", "曼谷"
    };

    return internationalDestinations.contains(destinationCity);
}
